package cmd

import (
	"context"
	"os"
	"os/signal"
	"syscall"

	"github.com/fatih/color"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "mig2kwdb",
	Short: "Migrate data to kwdb",
}

func createContext() context.Context {
	ctx, cancel := context.WithCancel(context.Background())

	ch := make(chan os.Signal, 1)
	go cleanupHandler(ch, cancel)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

	return ctx
}

// cleanupHandler handles the SIGINT and SIGTERM signals.
func cleanupHandler(c <-chan os.Signal, cancel context.CancelFunc) {
	errorColor := color.New(color.FgRed, color.Bold)
	s := <-c
	
	cancel()
	errorColor.Println("\n=====Received signal:", s, ", stop the task, please wait...=====")
}
func init() {

	// 添加子命令
	rootCmd.AddCommand(migrateCmd)
	rootCmd.AddCommand(verifyCmd)
}

// Execute 是应用的入口点
func Execute() error {
	ctx := createContext()
	return rootCmd.ExecuteContext(ctx)
}
